package ink.yql.service.Impl;

import ink.yql.dao.UserDao;
import ink.yql.model.User;
import ink.yql.service.UserService;
import ink.yql.util.MyRandom;
import ink.yql.util.RestObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yql.myutil.MyDate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private HttpServletRequest req;

    @Override
    public RestObject loginByPhoneAndPwd(String phone, String pwd) {
        //判断手机号侧长度
        if (phone.length() != 11) {
            return new RestObject("400", "手机号码长度不对!!!", null);
        }
        if (pwd == null || pwd.trim().length() == 0) {
            return new RestObject("400", "输入密码为空!!!", null);
        }
        // 查询数据库
        User user = userDao.getByPhone(phone);

        // 判断手机号对应的用户是否存在
        if (user == null || user.getUid() == null) {
            return new RestObject("400", "手机号为注册!!!", null);
        }
        // 判断密码是否正确
        if (user.getUpwd() == null || user.getUpwd().trim().length() == 0 || !pwd.trim().equals(user.getUpwd().trim())) {
            return new RestObject("400", "密码错误!!!", null);
        }
        // 存在,更新登录时间和ip
        userDao.updateLoginTimeAndIp(new Date(), req.getRemoteAddr(), user.getUid());
        // 设置登录用户
        req.getSession().setAttribute("user", user);

        return RestObject.builder().code("200").message("用户登录成功").data(user).build();
    }

    @Override
    public RestObject loginByPhoneAndCode(String phone, String code) {
        // 获取session中的验证码
        Map map = (Map) req.getSession().getAttribute("code");
        // 判断验证码是否存在
        if (map == null || map.get("code").toString() == null) {
            return RestObject.builder().code("400").message("请先获取验证码!!!").build();
        }
        String verificationCode = map.get("code").toString();
        MyDate time = (MyDate) map.get("time");
        // 判断验证码是否过期
        if ((System.currentTimeMillis() - time.getTime()) / 1000 / 60 > 5) {
            return RestObject.builder().code("401").message("验证码已失效").build();
        }
        User user = userDao.getByPhone(phone);
        // 判断手机号对应的用户是否存在
        if (user == null || user.getUid() == null) {
            // 如果不存在创建一个随机用户
            User randomUser = MyRandom.randomUser();
            randomUser.setUphone(phone);
            randomUser.setUloginTime(new MyDate().toString());
            randomUser.setUloginIp(req.getRemoteAddr());
            randomUser = userDao.getByPhone(phone);
            return RestObject.builder()
                      .code("200")
                      .message("登录成功")
                      .data(randomUser).build();
        }
        // 记录最后登录时间和ip
        userDao.updateLoginTimeAndIp(new Date(), req.getRemoteAddr(), user.getUid());
        // 响应数据
        return RestObject.builder()
                  .code("200")
                  .message("登录成功")
                  .data(user).build();
    }

    @Override
    public RestObject loginSendCode(String phone) {
        // 判断手机号是否规范
        if (phone == null || phone.trim().length() == 0) {
            return RestObject.builder().code("400").message("手机号不能为空!!!").build();
        }
        if (phone.trim().length() != 11) {
            return RestObject.builder().code("400").message("手机号格式不对!!!").build();
        }
        // 发送手机验证码
        String code = MyRandom.sendPhoneCode(phone);
        //获取session
        HttpSession session = req.getSession();
        // 创建map存储验证码和验证创建的时间
        HashMap map = new HashMap(2);
        // 添加验证码
        map.put("code", code);
        // 添加验证码创建的时间
        map.put("time", new MyDate());
        // 将map添加到session中
        session.setAttribute("code", map);
        // 响应数据
        return RestObject.builder().code("200").message("短信发送成功").build();
    }

    @Override
    public RestObject getById(Integer id) {
        // id不为空
        if (id == null) {
            return RestObject.builder().code("400").message("请传输正确的id").build();
        }
        // 获取信息
        User user = userDao.getByUid(id);
        // 该用户是否存在
        if (user == null) {
            return RestObject.builder().code("400").message("请传输正确的id").build();
        }
        return RestObject.builder().code("200").message("查询成功").data(user).build();
    }

    @Override
    public RestObject updateById(User user) {
        // 传输的用户信息是否合理
        if (user == null || user.getUid() == null) {
            return RestObject.builder().code("400").message("请传输一个正确的用户数据").build();
        }
        // 查询该用户的信息
        User daoByUid = userDao.getByUid(user.getUid());
        // 如果没有该用户
        if (daoByUid == null) {
            return RestObject.builder().code("404").message("该用户不存在").build();
        }
        // 判断信息是否有修改
        if (daoByUid.equals(user)) {
            return RestObject.builder().code("200").message("信息已保存").build();
        }
        // 将修改后的信息(可以修改的数据)更改到数据库
        daoByUid.setUsummary(user.getUsummary());
        daoByUid.setUsex(user.getUsex());
        daoByUid.setUbirthday(user.getUbirthday());
        daoByUid.setUprovince(user.getUprovince());
        daoByUid.setUcity(user.getUcity());
        daoByUid.setUaddress(user.getUaddress());
        // 更新数据
        Integer ret = userDao.updateByUid(daoByUid);
        // 返回响应信息
        return RestObject.builder().code("200").message("数据保存成功").build();
    }

    @Override
    public RestObject logout() {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null|| user.getUid()==null){
            return RestObject.builder().code("404").message("未登录").build();
        }
        session.invalidate();
        return RestObject.builder().code("200").message("登出成功").build();
    }
}
